<template>
  <view class="container" v-if="isLoaded">
    <!-- 地址 -->
    <scroll-view scroll-y style="height: 100vh">
      <view class="wrapper">
        <!-- address -->
        <view class="edit-c" v-if="m_addressList.length > 0">
          <view class="address-c">
            <view class="l">
              <view class="a">{{
                m_addressList[m_address_idx].FPrCityArea
              }}</view>
              <view class="u">{{ m_addressList[m_address_idx].FAddress }}</view>
              <view class="u" style="">
                <view class="n">{{
                  m_addressList[m_address_idx].FConsignee
                }}</view>
                <view class="p">{{ m_addressList[m_address_idx].FPhone }}</view>
              </view>
            </view>
            <view class="r">
              <!--   <uni-icons
                type="trash"
                size="30"
                style="margin-right: 5px"
                v-on:tap="DelAddress(address)"
              /> -->
              <u-icon
                name="edit-pen"
                size="30"
                v-on:tap="editAddress(m_addressList[m_address_idx])"
              />
            </view>
          </view>
        </view>
        <view class="add-c" v-if="m_addressList.length == 0">
          <view class="btn-add" v-on:tap="newAddress">新增收货地址</view>
        </view>
        <view class="add-c" v-if="m_addressList.length > 0">
          <view class="btn-add" v-on:tap="oca">更换收货地址</view>
        </view>

        <!-- 商品 -->
        <view class="gs">
          <view class="t"> 商品列表 </view>
          <view class="product" v-for="(good, key) in cart" :key="key">
            <image
              :src="imageUrl + good.FProImage"
              mode="aspectFit"
              class="image"
            />

            <view class="content">
              <view class="name">{{ good.FName }}</view>
            </view>
            <view class="p-c">
              <view class="p">￥{{ good.FPrice }}</view>
              <view class="q">x{{ good.FQty }}</view>
            </view>
          </view>
          <view style="padding: 10px 14px; display: flex; align-items: center">
            <u--input
              placeholder="添加订单备注"
              border="surround"
              v-model="form.remark"
              :maxlength="50"
            ></u--input>
          </view>
        </view>

        <!-- 金额 -->
        <view class="js">
          <view class="i">
            <view class="l">商品原价</view>
            <view class="r fwb"
              ><text class="s">￥</text>{{ tMoney.toFixed(2) }}</view
            >
          </view>
          <view class="i">
            <view class="l">优惠金额</view>
            <view class="r fwb red"
              ><text class="s">- ￥</text>{{ reduceAmount.toFixed(2) }}</view
            >
          </view>
          <view class="i">
            <view class="l;">运费</view>
            <view class="r fwb"
              ><text class="s">￥</text>{{ m_ExpMoney.toFixed(2) }}</view
            >
          </view>
          <view class="i"
            ><view class="l">优惠券</view>
            <view class="r" style="color: #858585" v-if="ccu.length == 0"
              >暂无优惠券可用</view
            >
            <view
              v-else
              class="r"
              style="
                color: rgb(254, 16, 17);
                font-weight: bold;
                display: flex;
                align-items: center;
                margin-right: -10px;
              "
              v-on:tap="onCouponPopup"
              >{{
                m_cid == 0
                  ? ccu.length + "张可用"
                  : ccu.find((i) => i.FItemID == m_cid).FName
              }}
              <u-icon
                name="arrow-right"
                size="14"
                style="margin-left: 4px"
              ></u-icon
            ></view>
          </view>

          <view class="i" style="border-top: 1px solid #f5f5f5">
            <view class="l"></view>
            <view class="r"
              >共计{{ tCount }}件,合计:
              <text class="s red" style="margin-left: 4px">￥</text
              ><text class="s fwb red" style="font-size: 14px">{{
                (tMoney - reduceAmount + send).toFixed(2) > 0
                  ? (tMoney - reduceAmount + send).toFixed(2)
                  : 0
              }}</text></view
            >
          </view>
        </view>

        <!-- 支付方式start -->
        <view class="payment-c">
          <text class="pay-title">支付方式</text>
          <view
            class="pay-method"
            v-for="(item, index) in m_payMethods"
            :key="item.value"
          >
            <u-icon
              :label="item.label"
              :name="item.name"
              :color="item.color"
              size="22"
            ></u-icon>
            <u-icon
              v-if="item.isShow"
              :name="item.isPayMethod ? item.selected : item.unSelected"
              color="#a78851"
              size="22"
              @click="onCheckPay(index)"
            ></u-icon>
            <!-- <view v-else>余额不足</view> -->
            <view
              v-else
              style="display: flex; align-items: center"
              @click="onRecharge"
            >
              余额不足，请充值
              <image
                class="width-30 height-30 shrink0"
                src="/static/images/my/icon_arrow.png"
              />
            </view>
          </view>
        </view>
        <!-- 支付方式end -->

        <!-- 提交订单按钮 -->
        <view class="b">
          <view class="btn" v-on:click="onOrderSubmit"> 提交订单 </view>
        </view>
      </view>
    </scroll-view>

    <li-coupon-popup
      ref="couponPopup"
      :cid="m_cid"
      :ccu="ccu"
      :ccnu="ccnu"
      v-on:onCidChange="onCidChange($event)"
    />
    <lee-popup :show="m_show" @open="open" @close="close">
      <view class="popup">
        <view
          class="address-c"
          v-for="(address, index) in m_addressList"
          :key="index"
          v-on:tap="(m_address_idx = index), (m_show = false)"
        >
          <view class="l">
            <view class="a">{{ address.FPrCityArea }}</view>
            <view class="u">{{ address.FAddress }}</view>
            <view class="u" style="">
              <view class="n">{{ address.FConsignee }}</view>
              <view class="p">{{ address.FPhone }}</view>
            </view>
          </view>
          <view class="r">
            <!--    <image
              style="width: 17px; height: 17px"
              v-if="m_address_idx == index"
              src="/static/images/icon-select.png"
            />
            <image
              style="width: 17px; height: 17px"
              v-else
              src="/static/images/noSelect.png"
            /> -->
          </view>

          <view
            v-if="m_address_idx == index"
            style="
              position: absolute;
              right: 0;
              top: 0;
              width: 0;
              height: 0;
              border-top: 15px solid #fe0203;
              border-right: 15px solid #fe0203;
              border-bottom: 15px solid transparent;
              border-left: 15px solid transparent;
            "
          ></view>
          <view
            v-if="m_address_idx == index"
            style="
              position: absolute;
              right: 0;
              top: 0;
              width: 18px;
              height: 18px;
              line-height: 18px;
              text-align: center;
              color: #fff;
            "
            >√</view
          >
        </view>
      </view>
    </lee-popup>
  </view>
</template>

<script>
import { computed, reactive, ref } from "@vue/composition-api";
import {
  uGetStorageSync,
  uModal,
  uNavigateBack,
  uNavigateTo,
  uToast,
} from "../../utils/uniUtils";
import { reqPost } from "../../common/http.request";
import { useShop } from "../../store/useShop";
import { storeToRefs } from "pinia";

export default {
  async onShow() {
    try {
      await this.GetAddressList();
      await useShop().GetShoppingCart();
      if (this.m_addressList.length > 0) {
        await this.AccExpMoney();
      }
      await this.GetCouponList();
      this.isLoaded = true;
    } catch (error) {
      this.isLoaded = !true;
      console.log("error", error);
      uToast("初始化失败~", "error");
      setTimeout(() => {
        uNavigateBack();
      }, 1500);
    }
  },

  setup(props, context) {
    /*    onMounted(async function () {
      try {
        await GetAddressList();
        if (m_addressList.value.length > 0) {
          await AccExpMoney();
        }
        isLoaded.value = true;
      } catch (error) {
        isLoaded.value = !true;
        console.log("error", error);
        uToast("初始化失败~", "error");
        setTimeout(() => {
          uNavigateBack();
        }, 1500);
      }
    }); */

    const m_addressList = ref([]);
    const m_payMethods = ref([
      {
        label: "微信支付",
        value: "wechatpay",
        name: "weixin-fill",
        selected: "checkmark-circle-fill",
        unSelected: "checkmark-circle",
        color: "#51b133",
        isPayMethod: true,
        isShow: true,
        id: 1,
      },
      /* {
        label: "余额支付",
        value: "balancepay",
        name: "rmb",
        selected: "checkmark-circle-fill",
        unSelected: "checkmark-circle",
        color: "#51b133",
        isPayMethod: false,
        isShow: false,
        id: 2,
      }, */
    ]);
    const couponPopup = ref(null);
    const payment_code = ref("wechatpay");
    const FPayId = ref(1);
    const balance = ref(0);
    const reduceAmount = ref(0);
    const send = ref(0);
    const m_ExpMoney = ref(0);
    const isLoaded = ref(false);
    const m_lock = ref(false);
    const { cart, tCount, tMoney } = storeToRefs(useShop());
    const form = reactive({
      remark: "",
    });

    const m_couponList = ref([]);
    const m_type = ref(0);
    const m_cid = ref(0);
    const MemberId = uGetStorageSync("member").MemberId;
    const m_address_idx = ref(0 - 1);

    async function GetCouponList() {
      const { Data } = await reqPost("GetCouponList", {
        MemberId,
        type: m_type.value,
      });
      m_couponList.value = Data;
    }

    const ccu = computed(() => {
      let arr = [];

      m_couponList.value.forEach((coupon) => {
        if (
          coupon.goodsList.length === 0 &&
          coupon.FMinValue <= useShop().tMoney
        ) {
          arr.push(coupon);
        } else if (coupon.goodsList.length > 0) {
          const couponFGoodIDs = coupon.goodsList.map((i) => i.FGoodID);
          const cartFGoodIDs = cart.value.map((i) => i.FGoodsID);

          const innerFoodIDs = couponFGoodIDs.filter((item) =>
            cartFGoodIDs.includes(item)
          );

          if (innerFoodIDs.length > 0) {
            const totalMoney = cart.value
              .filter((c) => innerFoodIDs.includes(c.FGoodsID))
              .reduce((p, c) => p + c.RealMoney, 0);

            if (totalMoney >= coupon.FMinValue) {
              arr.push(coupon);
            }
          }
        }
      });

      return arr;
    });

    const ccnu = computed(() => {
      let arr = [];

      m_couponList.value.forEach((coupon) => {
        if (
          coupon.goodsList.length === 0 &&
          coupon.FMinValue > useShop().tMoney
        ) {
          coupon.cr = `订单金额总价低于${coupon.FMinValue}元!`;

          arr.push(coupon);
        } else if (coupon.goodsList.length > 0) {
          const couponFGoodIDs = coupon.goodsList.map((i) => i.FGoodID);
          const cartFGoodIDs = cart.value.map((i) => i.FGoodsID);

          const innerFoodIDs = couponFGoodIDs.filter((item) =>
            cartFGoodIDs.includes(item)
          );

          if (innerFoodIDs.length > 0) {
            const totalMoney = cart.value
              .filter((c) => innerFoodIDs.includes(c.FGoodsID))
              .reduce((p, c) => p + c.RealMoney, 0);

            if (totalMoney < coupon.FMinValue) {
              coupon.cr = `指定商品总价不足${coupon.FMinValue}元!`;
              arr.push(coupon);
            }
          } else {
            coupon.cr = "未选购指定商品！";
            arr.push(coupon);
          }
        }
      });

      return arr;
    });

    function newAddress() {
      uNavigateTo("/pages/user/newAddress/newAddress");
    }

    async function GetAddressList() {
      m_addressList.value = (await reqPost("GetAddressList")).Data;
      if (m_addressList.value.length > 0) {
        m_address_idx.value = 0;
        const idx = m_addressList.value.findIndex(
          (item) => item.FDefault == "1"
        );
        if (idx >= 0) {
          m_address_idx.value = idx;
        }
      }
    }

    async function AccExpMoney() {
      if (m_addressList.value.length == 0) {
        return;
      }

      m_ExpMoney.value = (
        await reqPost("AccExpMoney", {
          strJson: JSON.stringify({
            // FCmpID: "",
            Pid: m_addressList.value[0].FPrvID,
            Cid: m_addressList.value[0].FCityID,
            ArID: m_addressList.value[0].FAreaID,
            ImportFlag: 0,
          }),
        })
      ).Data;
    }

    /*    watch(
      balance,
      (n, o) => {
        if (n < tMoney.value) {
          // 判断余额是否大于商品价格
          m_payMethods.value[1].isShow = false;
        } else {
          m_payMethods.value[1].isShow = true;
        }
      },
      {
        immediate: true,
        deep: true,
      }
    ); */

    async function DelAddress(address) {
      if (address.FDefault == "1") {
        return uToast("默认地址不允许删除", "none");
      }
      if (await uModal("确定要删除吗？")) {
        let res = (
          await reqPost("DelAddress", {
            id: address.FItemID,
          })
        ).Data;

        if (res) {
          await GetAddressList();
          uToast("删除成功！");
        } else {
          uToast("删除失败！", "error");
        }
      }
    }

    function editAddress(address) {
      uNavigateTo("/pages/user/newAddress/newAddress?id=" + address.FItemID);
    }

    async function onOrderSubmit() {
      let J_FCouponMoney =
        m_cid.value == 0
          ? 0
          : ccu.value.find((i) => i.FItemID == m_cid.value).FValue;

      if (m_address_idx.value == -1) {
        uToast("请选择地址", "error");
        return;
      }

      if (m_addressList.value.length == 0) {
        uToast("请输入地址", "error");
        return;
      }

      if (m_lock.value) {
        return;
      }

      const m_address = m_addressList.value[m_address_idx.value];
      m_lock.value = true;
      try {
        const m_dt = (
          await reqPost("OrderSubmit", {
            J_Pid: m_address.FPrvID,
            J_Cid: m_address.FCityID,
            J_Arid: m_address.FAreaID,
            J_CmpID: 0,
            J_PayID: FPayId.value,
            J_FCouponID: m_cid.value,
            J_FCouponMoney,
            J_ExpMoney: m_ExpMoney.value,
            J_FImportFlag: 0,
            J_FBillFlag: "off", // 是否要发票
            J_FConsignee: m_address.FConsignee,
            J_FPrCityArea: m_address.FPrCityArea,
            J_FAddress: m_address.FAddress,
            J_FPhone: m_address.FPhone,
            J_FMessage: form.remark,
            type: "0",
            FSckillDetailID: null,
          })
        ).Data;

        const J_KInterID = m_dt.J_KInterID;
        uToast("订单保存成功~");
        setTimeout(() => {
          uNavigateTo(`/pages/order/OrderToPay?id=${J_KInterID}`);
        }, 1000);
      } catch (error) {
        console.log("error :>> ", error);
      } finally {
        m_lock.value = false;
      }

      console.log("onOrderSubmit");
    }

    function onCheckPay(index) {
      m_payMethods.value.forEach((e) => {
        e.isPayMethod = false;
      });
      m_payMethods.value[index].isPayMethod =
        !m_payMethods.value[index].isPayMethod;
      payment_code.value =
        m_payMethods.value[
          m_payMethods.value.findIndex((e) => e.isPayMethod)
        ].value;
      FPayId.value =
        m_payMethods.value[
          m_payMethods.value.findIndex((e) => e.isPayMethod)
        ].id;
    }

    function onRecharge() {
      console.log("onRecharge");
    }
    function onCidChange(e) {
      // console.log("e :>> ", e);
      m_cid.value = e;
      if (e == 0) {
        reduceAmount.value = 0;
      } else {
        reduceAmount.value = ccu.value.find(
          (i) => i.FItemID == m_cid.value
        ).FValue;
      }
    }

    function onCouponPopup() {
      // console.log("couponPopup.value", couponPopup.value);
      couponPopup.value.open();
    }

    const m_show = ref(false);
    function oca() {
      m_show.value = true;
    }

    function open() {
      console.log("open");
      m_show.value = true;
    }
    function close() {
      m_show.value = !true;

      console.log("close");
    }

    return {
      m_show,
      m_addressList,
      GetAddressList,
      newAddress,
      isLoaded,
      DelAddress,
      editAddress,
      cart,
      tCount,
      tMoney,
      form,
      onOrderSubmit,
      m_payMethods,
      payment_code,
      onCheckPay,
      onRecharge,
      balance,
      reduceAmount,
      send,
      AccExpMoney,
      m_ExpMoney,
      onCouponPopup,
      couponPopup,
      GetCouponList,
      m_couponList,
      ccu,
      ccnu,
      m_cid,
      onCidChange,
      m_address_idx,
      oca,
      open,
      close,
    };
  },
};
</script>

<style lang="scss" scoped>
@import "./scss/cartOrder.scss";
</style>
